import { ref } from "vue";

/*
 * @Date: 2023-03-30 16:59:24
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-04-09 16:10:38
 * @FilePath: \A19\frontend\src\utils\frequencyDataFromStream.ts
 */
export function createStreamSourceNode(
  stream: MediaStream,
  canvas: HTMLCanvasElement
) {
  const frameId = ref<number>(0);
  const c = canvas.getContext("2d") as CanvasRenderingContext2D;
  const W = canvas.width as number;
  const H = canvas.height as number;

  // stream.onaddtrack = () =>{
  //   console.log('track added');
  // }

  const audioContext = new AudioContext();
  if(stream.getAudioTracks().length === 0){
    console.log('no audio Track');
    
    return 
  }
  
  const audioSourceNode = audioContext.createMediaStreamSource(stream)
  const analyser = audioContext.createAnalyser();
  analyser.fftSize = 32;

  const bufferLength = analyser.frequencyBinCount;
  const dataArray = new Uint8Array(bufferLength);

  const linearUp = c.createLinearGradient(-W, 0, 0, 0);
  linearUp.addColorStop(1, "#998ee0");
  linearUp.addColorStop(0.6, "#e17dc2");
  linearUp.addColorStop(0, "#ef9393");
  
  console.log('draw');
  const draw = () => {
    analyser.getByteFrequencyData(dataArray);
    // analyser.getByteTimeDomainData(dataArray)
    const max = Math.max(...dataArray);
    const w = -(max * W) / 255 + H / 2 + 20
    // console.log(w);
    // console.log(canvas);
    

    c.save();
    c.clearRect(0, 0, W, H);
    c.fillStyle = linearUp;
    c.translate(W, 0);
    c.fillRect(0,0,w ,H)
    c.beginPath()
    c.arc(w,H/2,H/2,0,180)
    c.closePath()
    c.fill()
    c.restore();

    frameId.value = requestAnimationFrame(draw);
  };
  frameId.value = requestAnimationFrame(draw);

  audioSourceNode.connect(analyser);
  //   analyser.connect(audioContext.destination);

  const destorySourse = () => {
    console.log('destorySourse');
    c.clearRect(0, 0, W, H);
    cancelAnimationFrame(frameId.value);
    audioSourceNode.disconnect();
    analyser.disconnect();
  };

  return {
    destorySourse,
  };
}
